package exam;

import interceptor.InjectConnection;

import java.sql.Connection;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

import utils.Var;
import utils.SessionVar;
import utils.PageUtils;
import examinee.SearchInfo;
import examinee.ExamineeInfo;
import examinee.Examinee;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

/**
 * Created by IntelliJ IDEA.
 * User: Shawn
 * Date: 2009-6-29
 * Time: 15:22:04
 */
public class SearchAction {

  private Connection con;

  @InjectConnection
  public void setCon(Connection con) {
    this.con = con;
  }

  private SearchInfo searchInfo;
  private List<ExamineeInfo> elist;
  private Map<Long, TestPaperInfo> testMap;
  private int page;
  private long pageSum;
  private long sum;

  public String getTestScores() throws Exception {
    HttpSession session = ServletActionContext.getRequest().getSession();
    if (searchInfo == null) searchInfo = (SearchInfo) session.getAttribute(SessionVar.EXAMINEE_SEARCH_INFO);
    else session.setAttribute(SessionVar.EXAMINEE_SEARCH_INFO, searchInfo);

    //examinee list
    sum = Examinee.getExamineeSum(con, searchInfo);
    pageSum = sum / Var.PAGE_LENGTH + 1;
    page = PageUtils.getPage(page);
    long from = PageUtils.getFrom(page);
    elist = Examinee.getExamineeList(con, searchInfo, from, Var.PAGE_LENGTH);

    //examinee ids
    long[] ids = new long[elist.size()];
    for (int i = 0; i < elist.size(); i++) ids[i] = elist.get(i).getEid();

    //get test paper
    testMap = new HashMap<Long, TestPaperInfo>();
    List<TestPaperInfo> tests = TestPaper.getTestPapers(con, ids);
    for (TestPaperInfo info : tests) testMap.put(info.getEid(), info);

    return Var.ACTION_SUCCESS;
  }

  public SearchInfo getSearchInfo() {
    return searchInfo;
  }

  public void setSearchInfo(SearchInfo searchInfo) {
    this.searchInfo = searchInfo;
  }

  public List<ExamineeInfo> getElist() {
    return elist;
  }

  public Map<Long, TestPaperInfo> getTestMap() {
    return testMap;
  }

  public void setPage(int page) {
    this.page = page;
  }

  public int getPage() {
    return page;
  }

  public long getPageSum() {
    return pageSum;
  }

  public long getSum() {
    return sum;
  }

  private long eid;
  private ExamineeInfo einfo;
  private TestPaperInfo tinfo;
  private List<AnswerPaperInfo> alist;

  public String getTestDetail() throws Exception {
    tinfo = TestPaper.getTestPaper(con, eid);
    einfo = Examinee.getExaminee(con, eid);
    alist = AnswerPaper.getAnswerPaperList(con, tinfo.getTid());
    return Var.ACTION_SUCCESS;
  }

  public void setEid(long eid) {
    this.eid = eid;
  }

  public ExamineeInfo getEinfo() {
    return einfo;
  }

  public TestPaperInfo getTinfo() {
    return tinfo;
  }

  public List<AnswerPaperInfo> getAlist() {
    return alist;
  }
}
